//
//  EditUserView.m
//  AccuroScale
//
//  Created by Yongfeng Li on 5/6/14.
//  Copyright (c) 2014 Yongfeng Li. All rights reserved.
//

#import <AudioToolbox/AudioServices.h>
#import "EditUserView.h"
#import "AppDelegate.h"
#import "N_WgtData.h"
#import "MemberViewCtrl.h"

#include <arpa/inet.h>

//static uint16_t _nScalePort = 3000;
//static char _szScaleAddr[32] = "192.168.1.1";

//static char _szUpdUser[] = "UpdUser";
//static char _szUpgUser[] = "UpgUser";
//static char _szDisTagId[] = "DisTagId";

static short _nLastWgtVal = 0;
static NSString* _ScanRQCode = @"********";
//static BOOL _bNeedClrTagId = NO;
static BOOL _bComfirmEnd = NO;

/*@implementation UISegmentedControlIconText

-(id) initWithItems:(NSArray*)items {
    NSDictionary* aDict = [NSDictionary dictionaryWithObjectsAndKeys:@"Man", @"ic_male.png", @"ic_female.png", nil];
    //[self setImage:anImage forState:aState barMetrics:UIBarMetricsDefault];
    //[self setTitleTextAttributes:aDict forState:aState];
    //[self setDividerImage:anImage forLeftSegmentState:aState rightSegmentState:aState barMetrics:UIBarMetricsDefault];
    [self setImage:[UIImage imageNamed:@"ic_male.png"] forSegmentAtIndex:0];
    [self setTitleTextAttributes:aDict forState:UIControlStateNormal];
    [self setDividerImage:[UIImage imageNamed:@"ic_male.png"] forLeftSegmentState:UIControlStateSelected
        rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    return self;
}

@end*/

@implementation EditUserView {
  CGRect   popupRect;
	CGRect   hideRect;
	float    panelHeight;
	BOOL     _isPopup;
  NSString* _sEditName;
    
  UIImageView* _ivLoginTape;
  UILabel* _lblEditTips;
  UILabel* _lblScanTips;
    
  UITextField* _txtName;
  UIButton* _btnBodyWgt;
  UITextField* _txtBodyWgt;
  UISegmentedControl* _scWgtUnit;
    
  UITextField* _txtBodyHgt;
  UITextField* _txtHgtInch;
  UILabel* _lblHgtUnit;
  UILabel* _lblHgtInch;
  
  UITextField* _txtChestSize;
  UILabel* _lblChestUnit;
  UITextField* _txtWaistLine;
  UILabel* _lblWaistUnit;
  
  //UISegmentedControl* _scHgtUnit;
    
  //UITextField* _txtBornDate;
  UISegmentedControl* _scSex;
  UISegmentedControl* _scFitLvl;
    
  UILabel* _lblBornTip;
  UILabel* _lblConnTip;
  
  UIDatePicker* _dpBorn;
  NSDateFormatter* _dtFmt;
    
  UITextField* _txtPswd;
  UISwitch* _swtCardNo;
  UILabel* _lblScaleNo;
  UILabel* _lblCardNo;
  UISegmentedControl* _scRemoveFrGrp;
    
  UIButton* _btnDisable;
  UIButton* _btnSave;
  UIButton* _btnCancel;
    
  char _szScaleSn[16];
  NSString* _sTagIdNo;
  NSInteger _nUserId;
  //NcitWiFiDev* _socketSvr;
  //NcitWiFiDev* _socketScale;
    
  MemberViewCtrl* m_pViewCtrl;
    
  //ble or wifi scale parm
  BOOL _bClosedBle;
  double _dLastWgt;
  Byte _nLastWgtUnit;
  double _dLastHgt;
  Byte _nLastHgtUnit;
    
  Boolean _bNcitDevice;
  BOOL _bIsSuptBLe;
  BOOL _bRcvBLeData;
  BOOL _autoConnect;
  BOOL _bFirstConnBLe;
  BOOL _bContBleScale;
    
  NcitBleDevice* _ncitBleDev;
  //CBCentralManager *manager;
  //CBPeripheral *_peripheral;
  //NSMutableArray *hrConntMonitors;
  
  NSTimer* _wgtTimer;
    
  //QR code scan
  UIWgtMeasType* _wmtWgtType;
  
  /*BOOL _bQrReading;
  UIView* _viewQRcode;
  AVCaptureSession* _cptQRSession;
  AVCaptureVideoPreviewLayer* _cvpQRLayer;
  BOOL _bSendTagDevInfo;*/
  NSString* _sDevId;
}

- (void) _showAlert:(NSString *)title msg:(NSString*) sMsg {
    //@"Check your enter."
	UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message: sMsg
                                                     delegate:self cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil];
	[alertView show];
	//[alertView release];
}

- (id)initWithFrame:(CGRect)frame
{
  self = [super initWithFrame:frame];
  if (self) {
    // Initialization code
    [self initialize];
        
    popupRect = self.frame;
		hideRect = CGRectMake(popupRect.origin.x, popupRect.origin.y + popupRect.size.height, popupRect.size.width, 0);
		self.frame = hideRect;
		_isPopup = NO;
		//[self.layer setCornerRadius:6.0];
 		[self setClipsToBounds:YES];
  }
  
  _sDevId = @"";
  _wgtTimer = nil;
  return self;
}

- (void)initialize {
  _bClosedBle = NO;
  _dLastWgt = 0.0;
  _sEditName = @"";
    
  //QR code ini
  _wmtWgtType = nil;
  /*_bQrReading = NO;
  _viewQRcode = nil;
  _cptQRSession = nil;
  _cvpQRLayer = nil;
  _bSendTagDevInfo = NO;*/
    
  BOOL bIos7 = [[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0;
  CGFloat H = self.frame.size.height;
  CGFloat W = self.frame.size.width;
  CGFloat yDelta = (W > 500)?40: 30;
    
  UIImage* imgBkgd = [UIImage imageNamed:@"ic-user-tape.png"];
  _ivLoginTape = [[UIImageView alloc] initWithImage:imgBkgd];
  _ivLoginTape.frame = CGRectMake(-2, 0, self.frame.size.width+2, 26);
  [self addSubview:_ivLoginTape];
    
  _lblEditTips = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, 300, 26)];
  _lblEditTips.text = @"Create User";
  _lblEditTips.textColor = [UIColor whiteColor];
  _lblEditTips.backgroundColor = [UIColor clearColor];
  //_lblEditTips.tintColor = [UIColor whiteColor];
  _lblEditTips.font = [UIFont systemFontOfSize:(W>500)?17:14];
  [self addSubview:_lblEditTips];
    
  _lblScanTips = [[UILabel alloc] initWithFrame:CGRectMake(5, 40, 300, 26)];
  _lblScanTips.text = @"Create User";
  _lblScanTips.backgroundColor = [UIColor clearColor];
  _lblScanTips.tintColor = [UIColor blueColor];
  _lblScanTips.font = [UIFont systemFontOfSize:(W>500)?17:14];
  _lblScanTips.textAlignment = NSTextAlignmentCenter;
  [self addSubview:_lblScanTips];
  _lblScanTips.hidden = YES;
    
  CGFloat xPos = (W > 500)? ((W-240)/2): 40;
  CGFloat yPos = yDelta-5;
  _txtName = [[UITextField alloc] initWithFrame:CGRectMake(xPos, yPos, 240, 25)];
  _txtName.textColor = [UIColor blackColor];
	_txtName.backgroundColor = [UIColor whiteColor];
  _txtName.font = [UIFont systemFontOfSize:(W>500)?17:14];
  _txtName.borderStyle = UITextBorderStyleRoundedRect;
  //_txtName.placeholder = NSLocalizedString(@"NeMail", nil);//@"Name or Email";
  //_txtName.autocapitalizationType = UITextAutocapitalizationTypeNone;
  //[_txtName addTarget:self action:@selector(textNamedDidChange:) forControlEvents:UIControlEventEditingChanged];
  _txtName.keyboardType = UIKeyboardTypeEmailAddress;
  [_txtName addTarget:self action:@selector(nameOnClick:) forControlEvents:UIControlEventEditingDidBegin];
  [self addSubview:_txtName];
    
  xPos -= (W > 500)?24: 20;
  yPos += yDelta;
  _txtBodyWgt = [[UITextField alloc] initWithFrame:CGRectMake(xPos, yPos, (W>500)?75:60, 25)];
  _txtBodyWgt.textColor = [UIColor blackColor];
	_txtBodyWgt.backgroundColor = [UIColor whiteColor];
  _txtBodyWgt.font = [UIFont systemFontOfSize:(W>500)?17:14];
  _txtBodyWgt.borderStyle = UITextBorderStyleRoundedRect;
  _txtBodyWgt.placeholder = NSLocalizedString(@"Wgt", nil);//@"Weight";
  _txtBodyWgt.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
  [self addSubview:_txtBodyWgt];
  //_txtBodyWgt.hidden = YES;
  
  _btnBodyWgt = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnBodyWgt.frame = CGRectMake(xPos, yPos, (W>500)?75:60, 25);
  _btnBodyWgt.backgroundColor = [UIColor lightGrayColor];
  [_btnBodyWgt setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
  //[_btnBodyWgt setTitle:NSLocalizedString(@"Wgt", nil) forState:UIControlStateNormal];
  [_btnBodyWgt setTitle:@"WGT" forState:UIControlStateNormal];
  //_btnBodyWgt.layer.masksToBounds = YES;®
  _btnBodyWgt.layer.cornerRadius = 4;
  [_btnBodyWgt addTarget:self action:@selector(onTapGetBodyWgt:) forControlEvents:UIControlEventTouchUpInside];
  [self addSubview:_btnBodyWgt];
  //_btnBodyWgt.hidden = NO;
  
  
  BOOL bChn = [AppDelegate isLanguageChines];
    
  xPos +=  (W > 500)? 80: 65;
  _scWgtUnit = [[UISegmentedControl alloc] initWithFrame:CGRectMake(xPos, yPos, 60, 28)];
  //if(!bIos7)
      //[_scWgtUnit setSegmentedControlStyle:UISegmentedControlStylePlain];
  _scWgtUnit.tintColor = [UIColor orangeColor];
  [_scWgtUnit insertSegmentWithTitle:@"kg" atIndex:0 animated:NO];
  [_scWgtUnit insertSegmentWithTitle:@"kg" atIndex:1 animated:NO];
  _scWgtUnit.selectedSegmentIndex = bChn? 0: 1;
  [_scWgtUnit addTarget:self action:@selector(wgtUnitChged:) forControlEvents:UIControlEventValueChanged];
  [self addSubview:_scWgtUnit];
  _nLastWgtUnit = (Byte)_scWgtUnit.selectedSegmentIndex;
    
  if(W > 500)
    xPos += 80;
  else
    xPos += 80;
  CGFloat fHgtWid = bChn? 60: 50;
  _txtBodyHgt = [[UITextField alloc] initWithFrame:CGRectMake(xPos, yPos, fHgtWid, 25)];
  _txtBodyHgt.textColor = [UIColor blackColor];
	_txtBodyHgt.backgroundColor = [UIColor whiteColor];
  _txtBodyHgt.font = [UIFont systemFontOfSize:(W>500)?17:14];
  _txtBodyHgt.borderStyle = UITextBorderStyleRoundedRect;
  _txtBodyHgt.placeholder = NSLocalizedString(@"Hgt", nil);//@"Height";
  _txtBodyHgt.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
  _txtBodyHgt.textAlignment = NSTextAlignmentRight;
  [self addSubview:_txtBodyHgt];
    
  xPos += fHgtWid + 3; //W/2+fHgtWid+8
  _lblHgtUnit = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yPos, fHgtWid/2, 25)];
  _lblHgtUnit.textColor = [UIColor orangeColor];
	_lblHgtUnit.backgroundColor = [UIColor clearColor];
  _lblHgtUnit.text =  bChn?@"m":@"ft"; //@"M/D/yyyy";
  _lblHgtUnit.textAlignment = NSTextAlignmentLeft;
  _lblHgtUnit.font = [UIFont systemFontOfSize:(W>500)?15:11];
  [self addSubview:_lblHgtUnit];
    
  xPos += 13;//(W > 500)? (W/2 + 100): (W/2 + 70);
  _txtHgtInch = [[UITextField alloc] initWithFrame:CGRectMake(xPos, yPos, fHgtWid, 28)];
  _txtHgtInch.textColor = [UIColor blackColor];
  _txtHgtInch.backgroundColor = [UIColor whiteColor];
  _txtHgtInch.font = [UIFont systemFontOfSize:(W>500)?18:14];
  _txtHgtInch.borderStyle = UITextBorderStyleRoundedRect;
  _txtHgtInch.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
  _txtHgtInch.textAlignment = NSTextAlignmentRight;
  _txtHgtInch.placeholder = NSLocalizedString(@"Inch", nil);
  [self addSubview:_txtHgtInch];
    
  xPos +=  fHgtWid + 3;
  _lblHgtInch = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yPos, fHgtWid, 28)];
  _lblHgtInch.textColor = [UIColor orangeColor];
  _lblHgtInch.backgroundColor = [UIColor clearColor];
  _lblHgtInch.text =  @"inch"; //@"M/D/yyyy";
  _lblHgtInch.textAlignment = NSTextAlignmentLeft;
  _lblHgtInch.font = [UIFont systemFontOfSize:(W>500)?15:11];
  [self addSubview:_lblHgtInch];
  _nLastHgtUnit = _nLastWgtUnit;
  
  xPos = (W > 500)? ((W-240)/2): 40;
  yPos += yDelta;
  /*_lblChestTip = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yPos, fHgtWid * 3, 25)];
  _lblChestTip.textColor = [UIColor orangeColor];
  _lblChestTip.backgroundColor = [UIColor clearColor];
  _lblChestTip.text =  @"CHest Size:";
  _lblChestTip.textAlignment = NSTextAlignmentLeft;
  _lblChestTip.font = [UIFont systemFontOfSize:(W>500)?15:11];
  [self addSubview:_lblChestTip];*/

  _txtChestSize = [[UITextField alloc] initWithFrame:CGRectMake(xPos, yPos, (W>500)?110:90, 25)];
  _txtChestSize.textColor = [UIColor blackColor];
  _txtChestSize.backgroundColor = [UIColor whiteColor];
  _txtChestSize.font = [UIFont systemFontOfSize:(W>500)?17:14];
  _txtChestSize.borderStyle = UITextBorderStyleRoundedRect;
  _txtChestSize.placeholder = NSLocalizedString(@"Chest size", nil);
  _txtChestSize.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
  [self addSubview:_txtChestSize];
  
  xPos += (W>500)?115:95;
  _lblChestUnit = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yPos, fHgtWid, 28)];
  _lblChestUnit.textColor = [UIColor orangeColor];
  _lblChestUnit.backgroundColor = [UIColor clearColor];
  _lblChestUnit.text =  @"inch";
  _lblChestUnit.textAlignment = NSTextAlignmentLeft;
  _lblChestUnit.font = [UIFont systemFontOfSize:(W>500)?15:11];
  [self addSubview:_lblChestUnit];
  
  xPos += (W>500)?40:30;
  _txtWaistLine = [[UITextField alloc] initWithFrame:CGRectMake(xPos, yPos, (W>500)?110:90, 25)];
  _txtWaistLine.textColor = [UIColor blackColor];
  _txtWaistLine.backgroundColor = [UIColor whiteColor];
  _txtWaistLine.font = [UIFont systemFontOfSize:(W>500)?17:14];
  _txtWaistLine.borderStyle = UITextBorderStyleRoundedRect;
  _txtWaistLine.placeholder = @"Waist Line";
  _txtWaistLine.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
  [self addSubview:_txtWaistLine];
  
  xPos += (W>500)?115:95;
  _lblWaistUnit = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yPos, fHgtWid, 28)];
  _lblWaistUnit.textColor = [UIColor orangeColor];
  _lblWaistUnit.backgroundColor = [UIColor clearColor];
  _lblWaistUnit.text =  @"inch";
  _lblWaistUnit.textAlignment = NSTextAlignmentLeft;
  _lblWaistUnit.font = [UIFont systemFontOfSize:(W>500)?15:11];
  [self addSubview:_lblWaistUnit];

    
  xPos = (W > 500)? (W-180)/2: 70;
  yPos += yDelta;
  
  _scSex = [[UISegmentedControl alloc] initWithItems:@[@"Woman", @"Man"]];
  _scSex.frame = CGRectMake(xPos, yPos, 180, 28);
  _scSex.tintColor = [UIColor orangeColor];
  //[_scSex insertSegmentWithTitle:@"Male" atIndex:0 animated:NO];
  //[_scSex insertSegmentWithTitle:@"Female" atIndex:1 animated:NO];
 
  UIImage* iSex = [self getImageScale:@"ic_female.png" scale:1.0];
  [_scSex setImage:iSex forSegmentAtIndex:0];
  iSex = [self getImageScale:@"ic_male.png" scale:1.0];
  [_scSex setImage:iSex forSegmentAtIndex:1];
  [_scSex addTarget:self action:@selector(dtValChged:) forControlEvents:UIControlEventValueChanged];
  _scSex.selectedSegmentIndex = 1;
  [self addSubview:_scSex];
    
  yPos += yDelta * 1;
  _lblBornTip = [[UILabel alloc] initWithFrame:CGRectMake(20, yPos, 100, 26)];
  _lblBornTip.text = NSLocalizedString(@"BornDate", nil);//@"Born date";
  _lblBornTip.textColor = [UIColor orangeColor];
  _lblBornTip.backgroundColor = [UIColor clearColor];
  _lblBornTip.textAlignment = NSTextAlignmentLeft;
  _lblBornTip.font = [UIFont systemFontOfSize:(W>500)?17:14];
  [self addSubview:_lblBornTip];
  
  _scFitLvl = [[UISegmentedControl alloc] initWithFrame:CGRectMake(W/3-15, yPos + 6, W-W/3 + 9, 25)];
  [_scFitLvl insertSegmentWithTitle:@"Not Active" atIndex:0 animated:NO];
  [_scFitLvl insertSegmentWithTitle:@"Mid Active" atIndex:1 animated:NO];
  [_scFitLvl insertSegmentWithTitle:@"Very Active" atIndex:2 animated:NO];
  [self addSubview:_scFitLvl];

  
  CGFloat xOffSet = bIos7? 0 : 18;
  xPos = (W>500)? W-160: W/2+5-xOffSet;
  _lblConnTip = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yPos, 90, 26)];
  _lblConnTip.text = @""; //@"BLE...";
  _lblConnTip.textColor = [UIColor orangeColor];
  _lblConnTip.textAlignment = NSTextAlignmentRight;
  _lblConnTip.backgroundColor = [UIColor clearColor];
  _lblConnTip.font = [UIFont systemFontOfSize:(W>500)?17:14];
  [self addSubview:_lblConnTip];
    
  //yPos = yDelta * 4 + 8;
  yPos += yDelta * 1.25;
  _dpBorn = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, yPos, self.frame.size.width, 162)];
  _dpBorn.backgroundColor = [UIColor whiteColor];
  //_dpBorn.font = [UIFont systemFontOfSize:12];
  _dpBorn.datePickerMode = UIDatePickerModeDate;

  _dpBorn.minimumDate = [[NSDate date] dateByAddingTimeInterval:-60*60*24*365*100];
  _dpBorn.maximumDate = [NSDate date];
  [_dpBorn setDate:[[NSDate date]dateByAddingTimeInterval:-60*60*24*365*30]];
  //_dpBorn.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
  [_dpBorn setHidden:NO];
  //_dpBorn.dataSource = self;
  //_dpBorn.delegate = self;
  //[_dpBorn.delegate addTarget:self action:@selector(datePickerValChged:) forControlEvents:UIControlEventValueChanged];
  
  _dpBorn.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.0];
  [_dpBorn addTarget:self action:@selector(dtValChged:) forControlEvents:UIControlEventValueChanged];
  [self addSubview:_dpBorn];
  
  //UIImage* iBtn = [UIImage imageNamed:@"Ic-key.png"];
  //if(bIos7) {
    //iBtn = [iBtn imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  //}
  _dtFmt = [[NSDateFormatter alloc]init];
  if([AppDelegate isLanguageChines])
    [_dtFmt setDateFormat:@"yyyy-MM-dd"];
  else
    [_dtFmt setDateFormat:@"MM/dd/yyyy"];
    
  //passsword for upgrate
  xPos = (W > 500)? ((W-240)/2): 40;
  yPos = yDelta * 2 - 5;
  _txtPswd = [[UITextField alloc] initWithFrame:CGRectMake(xPos, yPos, 240, 25)];
  _txtPswd.textColor = [UIColor blackColor];
	_txtPswd.backgroundColor = [UIColor whiteColor];
  _txtPswd.font = [UIFont systemFontOfSize:(W>500)?17:14];
  _txtPswd.borderStyle = UITextBorderStyleRoundedRect;
  _txtPswd.placeholder = NSLocalizedString(@"Pswd", nil);//@"Password";
  _txtPswd.secureTextEntry = YES;
  [self addSubview:_txtPswd];
    
  yPos = _lblConnTip.frame.origin.y;
  //_swtCardNo = [[UISwitch alloc] initWithFrame:CGRectMake(W-60-xOffSet, yPos, 55, 26)];
  _swtCardNo = [[UISwitch alloc] initWithFrame:CGRectMake(20, yPos+50, 55, 26)];
  _swtCardNo.on = NO;
  _swtCardNo.backgroundColor = [UIColor clearColor];
  [_swtCardNo addTarget:self action:@selector(dtValChged:) forControlEvents:UIControlEventValueChanged];
  [self addSubview:_swtCardNo];
    
  xPos = (W-200)/2; //60
  yPos += yDelta; //150
  _lblCardNo = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yPos, 200, 26)];
  _lblCardNo.text = @"...Tag ID...";
  _lblCardNo.textColor = [UIColor blackColor];
  _lblCardNo.textAlignment = NSTextAlignmentCenter;
  _lblCardNo.backgroundColor = [UIColor clearColor];
  _lblCardNo.font = [UIFont systemFontOfSize:(W>500)?17:14];
  [self addSubview:_lblCardNo];
    
  yPos += yDelta; //180
  _lblScaleNo = [[UILabel alloc] initWithFrame:CGRectMake(xPos, yPos, 200, 26)];
  _lblScaleNo.text = @"...Scale SN...";
  _lblScaleNo.textColor = [UIColor blackColor];
  _lblScaleNo.textAlignment = NSTextAlignmentCenter;
  _lblScaleNo.backgroundColor = [UIColor clearColor];
  _lblScaleNo.font = [UIFont systemFontOfSize:(W>500)?17:14];
  [self addSubview:_lblScaleNo];
    
  xPos = (W > 500)? (W-280)/2: 20;
  yPos += yDelta + 10; //220
  _scRemoveFrGrp = [[UISegmentedControl alloc] initWithFrame:CGRectMake(xPos, yPos, 280, 26)];
  _scRemoveFrGrp.tintColor = [UIColor orangeColor];
  [_scRemoveFrGrp insertSegmentWithTitle:@"Not Remove From" atIndex:0 animated:NO];
  [_scRemoveFrGrp insertSegmentWithTitle:@"Remove From Group" atIndex:1 animated:NO];
  _scRemoveFrGrp.selectedSegmentIndex = 1;
  [_scRemoveFrGrp addTarget:self action:@selector(wgtUnitChged:) forControlEvents:UIControlEventValueChanged];
  [self addSubview:_scRemoveFrGrp];
  
  //disable button
  yPos += yDelta * 2 + 10; //290
  _btnDisable = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnDisable.frame = CGRectMake(self.frame.size.width/2-75, yPos, 150, 22);
  //[_btnSave setImage:iBtn forState:UIControlStateNormal];
  _btnDisable.backgroundColor = [UIColor whiteColor];
  _btnDisable.layer.masksToBounds = YES;
  _btnDisable.layer.cornerRadius = 8;
  [_btnDisable setTitle:NSLocalizedString(@"DisableID", nil)/*@"  Save"*/ forState:UIControlStateNormal];
  //[_btnLogin setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
  [_btnDisable addTarget:self action:@selector(doSaveAction:) forControlEvents:UIControlEventTouchUpInside];
  [self addSubview:_btnDisable];
  
  yPos = H - 36;
  UIImage* iBtn = [UIImage imageNamed:@"ic-floppy.gif"];
  if(bIos7)
    iBtn = [iBtn imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  _btnSave = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnSave.frame = CGRectMake((W>500)?160:40, yPos, 100, 26);
  [_btnSave setImage:iBtn forState:UIControlStateNormal];
  _btnSave.backgroundColor = [UIColor lightGrayColor];
  _btnSave.layer.masksToBounds = YES;
  _btnSave.layer.cornerRadius = 8;
  //[_btnLogin setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
  [_btnSave addTarget:self action:@selector(doSaveAction:) forControlEvents:UIControlEventTouchUpInside];
  [self addSubview:_btnSave];
  
  iBtn = [UIImage imageNamed:@"ic-pencil-x.gif"];
  if(bIos7)
    iBtn = [iBtn imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
  _btnCancel = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  _btnCancel.frame = CGRectMake((W>500)?(W-260): (W/2 + 30), yPos, 100, 26);
  [_btnCancel setImage:iBtn forState:UIControlStateNormal];
  _btnCancel.backgroundColor = [UIColor lightGrayColor];
  _btnCancel.layer.masksToBounds = YES;
  _btnCancel.layer.cornerRadius = 8;
  [_btnCancel setTitle:NSLocalizedString(@"Cancel", nil)/*@"  Cancel"*/ forState:UIControlStateNormal];
  [_btnCancel addTarget:self action:@selector(doSaveAction:) forControlEvents:UIControlEventTouchUpInside];
  [self addSubview:_btnCancel];

  _nUserId = 0;
    
  //ble and wifi scale init
  _bNcitDevice = NO;
    
  _autoConnect = YES;
  _bIsSuptBLe = YES;
  _bRcvBLeData = NO;
   
  _bFirstConnBLe = YES;
  _bContBleScale = NO;
    
  //_socketSvr = nil;
  //_socketScale = nil;
    
  //[self initBLEScale];
}

- (MemberViewCtrl *)viewController {
    UIResponder *responder = self;
    while (![responder isKindOfClass:[MemberViewCtrl class]]) {
        responder = [responder nextResponder];
        if (nil == responder) {
            break;
        }
    }
    return (MemberViewCtrl *)responder;
}

- (void) onTapGetBodyWgt:(id)sender
{
  //_lblScanTips.text = @"Get WGT";
  [self endEditing:YES];
    
  _btnBodyWgt.hidden = YES;
  _txtBodyWgt.hidden = NO;
  if(_wmtWgtType == nil) {
    
    CGFloat xPos = 10, yPos = 10, fWidHgt = 100;
    CGRect frame = self.frame; //[[UIScreen mainScreen] bounds];
    CGFloat W = frame.size.width;
    CGFloat H = frame.size.height;
    if(W > H) {
      fWidHgt = H - yPos * 2.0;
      xPos = (W - fWidHgt) / 2;
    }
    else {
      fWidHgt = W - xPos * 2.0;
      yPos = (H - fWidHgt) / 2;
    }
    _wmtWgtType = [[UIWgtMeasType alloc] initWithFrame:CGRectMake(xPos, yPos, fWidHgt, fWidHgt)];
    [self addSubview:_wmtWgtType];
  }
  
  _wmtWgtType.hidden = NO;
  _wmtWgtType.wtDelegate = self;
  [_wmtWgtType setQRcodeScanUI];
  
  _txtBodyWgt.text = @"";
  _lblEditTips.text = @"Scan QR code then Step On WiFi Scale";
}

- (void) ScanedQRcode:(NSString*)sCode
{
  if(_wgtTimer != nil) {
    [_wgtTimer invalidate];
    _wgtTimer = nil;
  }
  
  _sDevId = [NSString stringWithString:sCode];
  _wgtTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(onWiFiMeasTimer) userInfo:nil repeats:YES];
  
  [_wmtWgtType rmvWgtTypeButs];
  _wmtWgtType.wtDelegate = nil;
  [_wmtWgtType removeFromSuperview];
  _wmtWgtType = nil;
}

- (void) onWiFiMeasTimer
{
  AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  
  NSString* sUrl = [NSString stringWithFormat:@"Mfw/%ld", (long)-9];
  NSDictionary* measInfo = @{
                             @"_sDevId": _sDevId,
                             @"_sTagId": @"222222",
                             @"_nType" : @"1"
                             };
  NSMutableURLRequest *request = [pApp requestWebApiRouter:@"PUT" url:sUrl data:measInfo];
  
  //NSURLSessionDataTask *task = [_netSession dataTaskWithRequest:request];
  //[task resume];
  NSData *data= [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
  if (data != nil) {
    NSString* sRecv = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
    if(sRecv == nil || sRecv.length < 9)
      return;
    
    NSError *e = nil;
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
    if(jsonArray == nil)
      return;
    
    for(NSDictionary *item in jsonArray) {
      NSString* sWgtVal = [item objectForKey:@"_fWgtVal"];
      NSString* sWgtUn = [item objectForKey:@"_nWgtUnit"];
      NSLog(@"Item: %@", item);
      
      _txtBodyWgt.text = [NSString stringWithFormat:@"%.1f", sWgtVal.floatValue];
      if(sWgtUn.integerValue == 1) {
        _scWgtUnit.selectedSegmentIndex = 0;
        _txtHgtInch.hidden = YES;
        _lblHgtInch.hidden = YES;
        _lblHgtUnit.text = @"m";
      }
      else {
        _scWgtUnit.selectedSegmentIndex = 1;
        _txtHgtInch.hidden = NO;
        _lblHgtInch.hidden = NO;
        _lblHgtUnit.text = @"ft";
      }
      _nLastWgtUnit = _scWgtUnit.selectedSegmentIndex;
    }
    
    //[_wgtTimer invalidate];
    //_wgtTimer = nil;
  }
}

-(void) viewDisappear {
  if(_wgtTimer != nil) {
    [_wgtTimer invalidate];
    _wgtTimer = nil;
  }
}

- (UIImage*) getImageScale:(NSString*) sImgName scale:(float)fRate
{
    UIImage* imgBkgd = [UIImage imageNamed:sImgName];
    UIGraphicsBeginImageContext(CGSizeMake(imgBkgd.size.width * fRate, imgBkgd.size.height * fRate));
    [imgBkgd drawInRect:CGRectMake(0, 0, imgBkgd.size.width * fRate, imgBkgd.size.height * fRate)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    BOOL bIos7 = [[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0;
    if(bIos7) {
        scaledImage = [scaledImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    }
    return scaledImage;
}

/*#pragma mark - picker datasource methods
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return 3;
}

#pragma mark - picker delegate
-(NSString *) pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return [YourArray objectAtIndex:row];//your array that contains data
}


// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect
{
    // Drawing code
}
*/

-(void)popupUser {
	_isPopup = YES;
  _nLastWgtVal = 0;
  m_pViewCtrl = [self viewController];
  [self initBLEScale];
    
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.2];
	[UIView setAnimationCurve:UIViewAnimationCurveLinear];
	[self setFrame:popupRect];
	[UIView commitAnimations];
    
    //connect with server
  //AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];

  
  //[m_pViewCtrl stopUserActindicator];
  _lblScanTips.hidden = !_swtCardNo.on;
  
  NSInteger nDateIdx = [AppDelegate isLanguageChines]?2:1;
  _dpBorn.subviews[0].subviews[0].subviews[nDateIdx].hidden = YES;
  [_btnSave setTitle:(_nUserId==0)?@"Save":@"Update" forState:UIControlStateNormal];
  
    
  return;
    
  //just for test
  //[pApp deleteDataHandler:Nil tip:NO];
}

- (void)hideUser {
  [m_pViewCtrl showTopButs];
	_isPopup = NO;
  [self hideKeyboard];
  //_socketSvr.svrDelegate = nil;
  //AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  //[pApp CloseScaleHost];
  //if(_bQrReading)
    //[self stopQRReading];
    
  _bClosedBle = YES;
  //if(_socketScale != nil)
    //_socketScale.svrDelegate = nil;
  [_ncitBleDev stopScan];
  [_ncitBleDev stopMeas];
    
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.2];
	[UIView setAnimationCurve:UIViewAnimationCurveLinear];
	[self setFrame:hideRect];
	[UIView commitAnimations];
    
  [m_pViewCtrl runstopIndicator:NO];
}

- (void) nameOnClick:(id)sender
{
    if(!_txtPswd.hidden) {
        _lblCardNo.text = @"...Scan Tag...";
        _lblScaleNo.text = @"...On scale...";
    }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [self hideKeyboard];
}

-(void) hideKeyboard
{
    [_txtName resignFirstResponder];
    [_txtBodyWgt resignFirstResponder];
    [_txtBodyHgt resignFirstResponder];
    [_txtHgtInch resignFirstResponder];
    [_txtPswd resignFirstResponder];
}

-(void) wgtUnitChged:(id)sender
{
  Byte nWgtUnit = (Byte)_scWgtUnit.selectedSegmentIndex;
  BOOL bLb = nWgtUnit == 1;
  if(nWgtUnit != _nLastWgtUnit) {
    _dLastWgt = _txtBodyWgt.text.doubleValue;
    _dLastHgt = _txtBodyHgt.text.doubleValue;
    if(_nLastHgtUnit == 1)
      _dLastHgt += _txtHgtInch.text.doubleValue / 12;
  }
        
  double dUnitWgt = _dLastWgt;//[_txtBodyWgt.text floatValue];
    
  if(nWgtUnit == 0) {
    if(_nLastWgtVal > 0)
      dUnitWgt = _nLastWgtVal / 10.0;
    else
      dUnitWgt = (_nLastWgtUnit == 0)?dUnitWgt: dUnitWgt / _KgtoLb;
        
    _dLastHgt = (_nLastHgtUnit == 0)? _dLastHgt: _dLastHgt * _FtToMeter;
        
    CGFloat W = self.frame.size.width;
    CGFloat xPos = (W > 500)? 385: 165;
    CGFloat yPos = (W > 500)? 75 : 55;
    _txtBodyHgt.frame = CGRectMake(xPos, yPos, 60, 25);
    xPos = (W > 500)? (xPos+63): (W/2+68);
    _lblHgtUnit.frame = CGRectMake(xPos, yPos, 60, 25);
    _lblHgtUnit.text = @"m";
    _txtHgtInch.hidden = YES;
    _lblHgtInch.hidden = YES;
        
    if(_dLastHgt > 0) {
      _txtBodyHgt.text = [NSString stringWithFormat:@"%.3f", _dLastHgt];
    }
  }
  else {
    if(_nLastWgtVal > 0)
      dUnitWgt = [self getVdrBleLbWgtVal];
    else
      dUnitWgt = (_nLastWgtUnit == 1)?dUnitWgt: dUnitWgt * _KgtoLb;
    
    _dLastHgt = (_nLastHgtUnit == 1)? _dLastHgt: _dLastHgt / _FtToMeter;
        
    CGFloat W = self.frame.size.width;
    CGFloat xPos = (W > 500)? 400: 165;
    CGFloat yPos = (W > 500)? 75: 55;
    _txtBodyHgt.frame = CGRectMake(xPos, yPos, 50, 25);
    xPos += 53;//W/2+58
    _lblHgtUnit.frame = CGRectMake(xPos, yPos, 50, 25);
        
    xPos += (W > 500)? 12: 12;//W/2+70
    _txtHgtInch.frame = CGRectMake(xPos, yPos, 50, 25);
        
    //xPos += 50;//W/2+70
    //_lblHgtInch.frame = CGRectMake(xPos, yPos, 50, 25);
     
    _lblHgtUnit.text = @"ft";
    _txtHgtInch.hidden = NO;
    _lblHgtInch.hidden = NO;
        
    if(_dLastHgt > 0) {
      _txtBodyHgt.text = [NSString stringWithFormat:@"%d", (int)_dLastHgt];
      float fInch = (_dLastHgt-(int)_dLastHgt) * 12;
      _txtHgtInch.text = [NSString stringWithFormat:@"%.0f", fInch];
    }
  }
    
  _dLastWgt = dUnitWgt;
  _nLastWgtUnit = nWgtUnit;
  _nLastHgtUnit = nWgtUnit;
  if(dUnitWgt > 0)
    _txtBodyWgt.text = [NSString stringWithFormat:@"%.2f", dUnitWgt];

  _lblChestUnit.text =  bLb?@"inch":@"cm";
  _lblWaistUnit.text =  bLb?@"inch":@"cm";
}

-(void) dtValChged:(id)sender
{
    [self hideKeyboard];
    if(sender == _swtCardNo) {
        AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        BOOL bNcitDevConn = [pApp isNcitDeviceConned];
        
        NSString* sTitle = _swtCardNo.on? [NSString stringWithFormat:@"Replace Tag ID for user: %@", _sEditName]: [NSString stringWithFormat:@"Create account for user: %@", _sEditName];
        _lblEditTips.text = sTitle;//_swtCardNo.on? @"Replace User's TagId":@"Creat Account";
        _txtName.hidden = _txtPswd.hidden = _swtCardNo.on;
        if(bNcitDevConn)
            _lblCardNo.text = @"...Scan Tag...";
        _lblScaleNo.text = @"...On scale...";
        
        //_lblScanTips.hidden = !_bQrReading;
        //if(!_swtCardNo.on)
        _lblScanTips.hidden = !_txtPswd.hidden;
    }
    else if(!_btnSave.hidden) {
        _lblBornTip.text = [_dtFmt stringFromDate: _dpBorn.date];
    }
  _scRemoveFrGrp.hidden = _swtCardNo.on || !_dpBorn.hidden;
    
    if(_swtCardNo.on) {
        _lblCardNo.text = _sTagIdNo;
        //_btnSave.enabled = NO;
    }
}


-(void) ChgCtrlsShowState:(BOOL)bHide
{
  //_txtName.hidden = bHide;
  _txtName.placeholder = bHide? NSLocalizedString(@"Email", nil): NSLocalizedString(@"NeMail", nil);
  _btnBodyWgt.hidden = bHide;
  _txtBodyWgt.hidden = bHide;
  _scWgtUnit.hidden = bHide;
  
  _txtBodyHgt.hidden = bHide;
  _lblHgtUnit.hidden = bHide;
  _txtHgtInch.hidden = bHide;
  _lblHgtInch.hidden = bHide;
  
  _txtChestSize.hidden = bHide;
  _txtWaistLine.hidden = bHide;
  _scFitLvl.hidden = bHide;
  _lblChestUnit.hidden = bHide;
  _lblWaistUnit.hidden = bHide;
  
  _dpBorn.hidden = bHide;
    
  CGFloat W = self.frame.size.width;
  CGFloat yPos = (W > 500)? 210: 154;
  
  _lblBornTip.frame = bHide?CGRectMake(10, yPos, W/2-5, 26): CGRectMake(10, yPos, 100, 26);
  //_lblBornTip.text =  bHide?@"Scan ID on scale...":@"Born Date";//if you have it
  _lblBornTip.text =  bHide? NSLocalizedString(@"ReplIdTip", nil): NSLocalizedString(@"BornDate", nil);
  //_lblConnTip.hidden = bHide;
  //_lblConnTip.frame = bHide?CGRectMake(self.frame.size.width/2 + 10, 113, 170, 26):CGRectMake(130, 113, 170, 26);
  //_lblConnTip.text = bHide? @"Tag Only": @"BLE...";
  //_lblConnTip.text = bHide? NSLocalizedString(@"TagOnly", nil): @"BLE...";
    
  _txtName.hidden = NO;
  _txtPswd.hidden = !bHide;
  _swtCardNo.on = NO;
  _swtCardNo.hidden = !bHide;
  _lblCardNo.hidden = !bHide;
  _lblScaleNo.hidden = !bHide;
  //_btnSave.hidden = bHide;
    
  _scRemoveFrGrp.hidden = !bHide;
  _btnDisable.hidden = !bHide;
    
  _btnSave.enabled = YES;
}

-(void) setUserInfo:(NSString*) sName sex:(short)nSex chest:(float)fChest waist:(float)fWaist wgt:(NSString*)sWgt wun:(short)nWun hgt:(NSString*)sHgt hun:(short)nHun
               born:(NSString*)sBorn fitLvl:(short)nAct bodyId:(NSInteger)nBodyId
{
    [self ChgCtrlsShowState:NO];
    _lblEditTips.text = (sName.length == 0)? @"Create User Info.": @"Edit User Info.";
    _txtName.autocapitalizationType = UITextAutocapitalizationTypeWords;
     //_txtName.placeholder = @"Name or Email";
    
    _txtName.text = sName;
    _txtBodyWgt.text = sWgt;
    _scWgtUnit.selectedSegmentIndex = nWun;
  
  if(fChest > 0)
    _txtChestSize.text = [NSString stringWithFormat:@"%0.1f", fChest];
  if(fWaist > 0)
    _txtWaistLine.text = [NSString stringWithFormat:@"%0.1f", fWaist];
    
    if(sHgt.length > 0) {
        _dLastWgt = sWgt.doubleValue;
        _nLastWgtUnit = nWun;
        _dLastHgt = sHgt.doubleValue;
        _nLastHgtUnit = nHun;
        
        [self wgtUnitChged:_scWgtUnit];
        /*if(nHun == 0) {
            _txtBodyHgt.text = sHgt;
            _lblHgtUnit.text = @"m";
            _txtHgtInch.hidden = YES;
            _lblHgtInch.hidden = YES;
        }
        else {
            float fHgt = sHgt.floatValue;
            int nHgtFt = (int)fHgt;
            float fHgtIn = fHgt - nHgtFt;
            _txtBodyHgt.text = [NSString stringWithFormat:@"%d", nHgtFt];
            _lblHgtUnit.text = @"ft";
            _txtHgtInch.text = [NSString stringWithFormat:@"%.0f", fHgtIn * 12];
            _txtHgtInch.hidden = NO;
            _lblHgtInch.hidden = NO;
        }*/
    }
    else {
        BOOL bChn = [AppDelegate isLanguageChines];
        _scWgtUnit.selectedSegmentIndex = bChn?0:1;
        _dLastWgt = 0.0;
        _nLastWgtUnit = _scWgtUnit.selectedSegmentIndex;
        _dLastHgt = 0.0;
        _nLastHgtUnit = _scWgtUnit.selectedSegmentIndex;
        
        _txtBodyHgt.text = @"";
        _txtHgtInch.text = @"";
        _lblHgtUnit.text =  bChn?@"m":@"ft";
        _txtHgtInch.hidden = bChn;
        _lblHgtInch.hidden = bChn;
    }
    //_scHgtUnit.selectedSegmentIndex = nHun;
    
    _scSex.selectedSegmentIndex = nSex;
    [_dpBorn setDate:[_dtFmt dateFromString:sBorn]];
    
    _nUserId = nBodyId;
    _sEditName = sName;
    _lblScanTips.hidden = YES;
    _btnSave.enabled = YES;
  
  BOOL bCarate = sName.length == 0;
  _btnBodyWgt.hidden = !bCarate;
  _txtBodyWgt.hidden = bCarate;
  
  _scFitLvl.selectedSegmentIndex = nAct;
}

-(void) ugdUserCardNo:(NSInteger)nBodyId sex:(short)nSex name:(NSString*) sName sn:(NSString*)sSn card:(NSString*)sCard
{
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    //if(_socketScale == nil && [pApp isNcitDeviceConned]) {
      //_socketScale = [[NcitWiFiDev alloc]init:inet_addr(_szScaleAddr) port: _nScalePort];
    //}
    _lblEditTips.text = [NSString stringWithFormat:@"Create account for user: %@", sName];
    [self ChgCtrlsShowState:YES];
    _txtName.text = @"";
    _txtName.autocapitalizationType = UITextAutocapitalizationTypeNone;
    if([sName rangeOfString:@"@"].location != NSNotFound)
        _txtName.text = sName;
    //_txtName.placeholder = @"Email for sign in";
    _txtPswd.text = @"";
    _scSex.selectedSegmentIndex = nSex;
    
    //_lblCardNo.text = @"...Tag ID...";
    _lblScaleNo.text = @"...Scale SN...";
    
    _nUserId = nBodyId;
    _sEditName = sName;
    
  //if login user
  //NSUserDefaults *userSetting = [NSUserDefaults standardUserDefaults];
    BOOL bSignedUser = pApp.m_nLoginBodyId == nBodyId;// [userSetting stringForKey:kBodyIdStr].integerValue == nBodyId;
    if (bSignedUser) {
        _swtCardNo.on = YES;
        [self dtValChged:_swtCardNo];
        _scRemoveFrGrp.hidden = YES;
    }
    _swtCardNo.enabled = !bSignedUser;
    
    //if(![sCard hasPrefix:@"**"])
    _lblCardNo.text = sCard;
    _sTagIdNo = sCard;
    if(![sSn hasPrefix:@"0000000000"])
        _lblScaleNo.text = sSn;
    
    BOOL bDisabled = [sCard hasSuffix:@"-Dis"];
    if(bDisabled) {
        [_btnDisable setTitle:NSLocalizedString(@"TagIdDis", nil) forState:UIControlStateDisabled];
    }
    else {
        [_btnDisable setTitle:NSLocalizedString(@"DisableID", nil) forState:UIControlStateDisabled];
    }
    _btnDisable.enabled = !bDisabled;
}

#pragma mark -
#pragma mark save data of profiles into core data
-(Boolean) saveBodyPrfData:(NSInteger) nBodyId card:(NSString*) sCardNo {
   AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  if(![pApp isNetWorkConnAvailable]) {
    return NO;
  }
  
  Boolean bOK = NO;
  NSInteger nGrpId = pApp.m_nLoginBodyId;
    
  NSString *sName = _txtName.text;
  NSString *sWgt = _txtBodyWgt.text;
  NSString *sHgt = _txtBodyHgt.text;
  double dHgt = [sHgt floatValue];
  float fHgtIn = 0;
  if(!_txtHgtInch.hidden) {
    fHgtIn = _txtHgtInch.text.floatValue / 12;
    dHgt += fHgtIn;
  }
  sHgt = [NSString stringWithFormat:@"%.3f", dHgt];
  
  NSString* sChesSize = _txtChestSize.text;
  NSString* sWaistLine = _txtWaistLine.text;
  
  NSString* sSn = @"0000000000";
  //NSString* sInitDtFmt = _dtFmt.dateFormat;
  
  NSString *sSex = [NSString stringWithFormat:@"%i", (int)_scSex.selectedSegmentIndex];
  NSString *sWun = [NSString stringWithFormat:@"%i", (int)(_scWgtUnit.selectedSegmentIndex+1)];
  NSString *sHun = [NSString stringWithFormat:@"%i", (int)(_txtHgtInch.hidden?1: 2)]; //(_scHgtUnit.selectedSegmentIndex+1)];
  NSString *sBorn = [_dtFmt stringFromDate:_dpBorn.date];
  NSString *sAth = [NSString stringWithFormat:@"%i", (short)_scFitLvl.selectedSegmentIndex];
  
  Boolean bNeedUpd = _nUserId > 0;
  if(bNeedUpd) {
    NSString* sUrl = @"Host/-2";
    NSDictionary *measInfo = @{
                               @"BodyId" : [NSString stringWithFormat:@"%ld", (long)_nUserId],
                               @"Email" : sName,
                               @"Password": @"111111",
                               @"GroupId" : [NSString stringWithFormat:@"%ld", (long)nGrpId],
                               @"LocationId" : @"-1",
                               @"Gender" : sSex,
                               @"BodyWgt" : sWgt,
                               @"WgtUnit" : sWun,
                               @"BodyHgt" : sHgt,
                               @"HgtUnit" : sHun,
                               @"BodyBirthDay" : sBorn,
                               @"FitLvl" : sAth,
                               @"ChestSize" : sChesSize,
                               @"WaistLine" : sWaistLine
                               };
  
    NSMutableURLRequest *request = [pApp requestWebApiRouter:@"PUT" url:sUrl data:measInfo];
    
    // 6.同步发送请求
    //[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    NSData *data= [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(data != nil) {
      NSString* sRecv = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
      sRecv = [sRecv substringWithRange: NSMakeRange(1, sRecv.length-2)];
      if([sRecv hasPrefix:@"Failed"]) {
        [self _showAlert:@"WAN Connection" msg: sRecv];
        return NO;
      }
      [pApp updateMembGroupInfo:_nUserId sn:sSn card:sCardNo email:sName chest:sChesSize waist:sWaistLine sex:sSex age:sBorn wgt:sWgt wun:sWun
                            hgt:sHgt hun:sHun fitLvl:sAth];
      [m_pViewCtrl refreshMembData];
    }
    return YES;
  }
  else {
    /*if(!_txtHgtInch.hidden) {
      float dHgt = sHgt.doubleValue;
      dHgt += _txtHgtInch.text.floatValue / 12;
      sHgt = [NSString stringWithFormat:@"%.3f", dHgt];
    }*/
  
  
    //insert, save on svr at first
    NSString* sUrl = @"Host/-1";
    NSDictionary *measInfo = @{
                             @"Email" : sName,
                             @"Password": @"111111",
                             @"GroupId" : [NSString stringWithFormat:@"%ld", (long)nGrpId],
                             @"LocationId" : @"-1",
                             @"Gender" : sSex,
                             @"BodyWgt" : sWgt,
                             @"WgtUnit" : sWun,
                             @"BodyHgt" : sHgt,
                             @"HgtUnit" : sHun,
                             @"BodyBirthDay" : sBorn,
                             @"FitLvl" : sAth,
                             @"ChestSize" : sChesSize,
                             @"WaistLine" : sWaistLine
                             };
    NSMutableURLRequest *request = [pApp requestWebApiRouter:@"PUT" url:sUrl data:measInfo];
    // 6.同步发送请求
    //[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    NSData *data= [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if (data != nil) {
      NSString* sRecv = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
      sRecv = [sRecv substringWithRange: NSMakeRange(1, sRecv.length-2)];
      if([sRecv hasPrefix:@"Sorry"] || [sRecv rangeOfString:@"error"].location != NSNotFound ) {
        [self _showAlert: sRecv msg: NSLocalizedString(@"ExistsName", nil)];
        AudioServicesPlaySystemSound(1112);
        return NO;
      }
    
      bOK = YES;
      NSArray*  listItems = [sRecv componentsSeparatedByString:@":"];
      if(listItems.count > 1) {
        NSString* sNewBodyId = listItems[1];
        NSInteger nNewBodyId = sNewBodyId.integerValue;
        if(listItems.count > 2)
          sCardNo = listItems[2];
        [pApp insertMembGroupInfo:nGrpId bodyId:nNewBodyId sn:sSn card:sCardNo email:sName chest:sChesSize waist:sWaistLine
                              sex:sSex age:sBorn wgt:sWgt wun:sWun hgt:sHgt hun:sHun isAhtlet:sAth];
        [m_pViewCtrl refreshMembData];
      }
    }
    return bOK;
  }

}

- (void) recvedScaleData:(NSMutableString *) sLine {
    if(sLine == nil)
        return;
    
    _bComfirmEnd = YES;
    
    if([sLine hasPrefix: @"bye!"]) {
      [m_pViewCtrl runstopIndicator:NO];
        return;
    }
    BOOL bNoreg = [sLine rangeOfString:@"Failed: No register"].location != NSNotFound;
    if(bNoreg) {
        if([sLine rangeOfString:@"with Join-In"].location != NSNotFound) {
            [self _showAlert: @"Alredy has a join-in Acct" msg:sLine];
        }
        //else if([sLine rangeOfString:@"No Join-In"].location != NSNotFound) {
            //NSArray* listItems = [sLine componentsSeparatedByString:@" "];
            //NSString* sTagId = [listItems objectAtIndex:7];
            //_lblCardNo.text = sTagId;
            //_btnSave.enabled = YES;
        //}
        return;
    }
    
    if([sLine hasPrefix: @"Failed"]) {
      [m_pViewCtrl runstopIndicator:NO];
        if([sLine hasSuffix:@"TagId!\r\n"])
            [self _showAlert: @"Issue happend" msg:sLine];
        else if(_swtCardNo.on)
            [self _showAlert: @"No scan Tag ID on scale" msg:sLine];
        else
            [self _showAlert: @"Check your input text" msg:sLine];
        return;
    }
    else if([sLine hasPrefix:@"TagId"]) {
        NSString* sDisTagId = [NSString stringWithFormat:@"%@-Dis", _lblCardNo.text];
        if([sDisTagId hasPrefix:@"Upd"])
            sDisTagId = [sDisTagId substringFromIndex:3];
        [self UpdUserTagInfo:sDisTagId del:NO];
        //[m_pViewCtrl updateUserInfo];
        [self _showAlert: @"Tag ID Disabled" msg: sLine];
        [self hideUser];
    }
    else {
        NSString* sMsg = (NSString*)sLine;
        NSRange rng = [sMsg rangeOfString:@"Id already taken"];
        if(rng.location != NSNotFound) {
            _btnSave.enabled = NO;
            sMsg = [sMsg substringToIndex:20];
            [self _showAlert: sMsg msg: NSLocalizedString(@"TagIdExits", nil)];
            AudioServicesPlaySystemSound(1112);
            return;
        }
    }
    
    NSArray* listItems = [sLine componentsSeparatedByString:@" "];
    NSUInteger nCount = listItems.count;//[listItems count]; //== 2 scand from RF reader
    if(nCount >= 6)
        return;
    
    if((!_txtPswd.hidden && !_lblCardNo.hidden) || _swtCardNo.on) {  //upgrade user and create a new acct
        if (nCount == 3) {
            NSString* sDevId = [listItems objectAtIndex:1];
            NSString* sCardNo = [listItems objectAtIndex:2];
            if([sCardNo hasSuffix:@"\r\n"])
                sCardNo = [sCardNo stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
            if(sCardNo.length > 15)
                sCardNo = [sCardNo substringToIndex:15];
            _lblCardNo.text = sCardNo;
            _lblScaleNo.text = sDevId;
            /*if(_socketSvr) {
              _socketSvr.svrDelegate = self;
              NSString* sCheckId = [NSString stringWithFormat:@"0000 %s: %@", _szTagIdCheck, sCardNo];
              [_socketSvr userSignin:(char *)[sCheckId UTF8String] Alert:YES];
            }*/
            [self hideKeyboard];
            if(_swtCardNo.on && ![sCardNo hasPrefix:@"Upd"])
                _btnSave.enabled = YES;
            return;
        }
        else if([sLine hasPrefix:@"Tag Id"]) {
            _lblCardNo.text = @"...???...";
            _btnSave.enabled = NO;
            [self _showAlert: sLine msg: NSLocalizedString(@"TagIdExits", nil)];//@"Please use different tag to do that"];
            return;
        }
        
        if(_swtCardNo.on) {
             [self _showAlert:@"User Update Tag" msg:[NSString stringWithFormat:@"%@", sLine]];
        }
        else {
            if([sLine rangeOfString:@"create"].location != NSNotFound) {
                if(_scRemoveFrGrp.selectedSegmentIndex == 0)
                    [self _showAlert:@"User's Account Created" msg:@"User unlink from group account. User can sign on iOS device or Accuro website!"];
                else
                    [self _showAlert:@"User's Account Created" msg:@"User still in group account. But user can sign on iOS device or Accuro website!"];
            }
            else {
                [self _showAlert:@"User Upgrade" msg:[NSString stringWithFormat:@"%@ (not include password)", sLine]];
            }
        }
        [self hideUser];
        [self UpdUserTagInfo:_lblCardNo.text del:(_scRemoveFrGrp.hidden == NO && _scRemoveFrGrp.selectedSegmentIndex == 0)];
        [m_pViewCtrl updateUserInfo: _swtCardNo.on bodyId:_nUserId newTag: _lblCardNo.text];
        return;
    }
    
    if(nCount > 2) {    //just update user info
        NSString* sBodyId = [listItems objectAtIndex:1];
        NSString* sCardNo = [listItems objectAtIndex:2];
        if([sCardNo hasSuffix:@"\r\n"])
            sCardNo = [sCardNo stringByReplacingOccurrencesOfString:@"\r\n" withString:@""];
        int nBodyId = sBodyId.intValue;
        BOOL bOK = nBodyId > 0;
        if(bOK) {
            [self saveBodyPrfData:sBodyId.integerValue card:sCardNo];
            [self hideUser];
            [m_pViewCtrl updateUserInfo:NO bodyId:0 newTag:nil];
        }
    }
}

- (void) UpdUserTagInfo:(NSString*) sCardNo del:(BOOL) bDelete
{
    /*NSString* sBodyId = [NSString stringWithFormat:@"%ld", (long)_nUserId];
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    NSManagedObjectContext* moCtx = pApp.managedObjectContext;
    NSMutableArray* userArry = [pApp loadSqliteGroupInfo:sBodyId grpId:@"0"];
    if(userArry.count > 0) {
        N_GroupInfo *nGrp = (N_GroupInfo *)[userArry objectAtIndex:0];
        if(bDelete) {
            [moCtx deleteObject:nGrp];
        }
        else if(_swtCardNo.on || [sCardNo hasSuffix:@"-Dis"]) {
            nGrp.scaleNo = _lblScaleNo.text;
            nGrp.cardNo = sCardNo;
            NSError *error;
            [moCtx save:&error];
        }
    }*/
}

- (Boolean) passCheckFields:(NSString*)sName pswd:(NSString*)sPswd
{
    if([sName caseInsensitiveCompare:@""] == NSOrderedSame) {
        [self _showAlert:@"Email not blank!" msg: @"Check your enter."];
        return NO;
    }
    if([sPswd caseInsensitiveCompare:@""] == NSOrderedSame) {
        [self _showAlert:@"Password not blank!" msg: @"Check your enter."];
        return NO;
    }
    NSRange rng = [sName rangeOfString:@"@"];
    if(rng.location == NSNotFound) {
        [self _showAlert:@"Email without '@'!" msg: @"Check your enter."];
        return NO;
    }
    rng = [sName rangeOfString:@"."];
    if(rng.location == NSNotFound) {
        [self _showAlert:@"Email without '.'!" msg: @"Check your enter."];
        return NO;
    }
    
    return YES;
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(_bComfirmEnd)
        return;
    
    switch (buttonIndex) {
        case 0: //YES应该做的事
            //_lblCardNo.text = @"YES";
            /*(if(_socketSvr) {
              _socketSvr.svrDelegate = self;
              NSString* sMsg = [NSString stringWithFormat:@"1234 %s: %li\r\n", _szDisTagId, (long)_nUserId];
              [_socketSvr userSignin:(char *)[sMsg UTF8String] Alert:YES];
            }*/
            break;
        case 1://NO应该做的事
            //_lblCardNo.text = @"NO";
            break;
    }
}

- (void) ugdMemberBodyInfo
{
  AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  BOOL bUpdCardNo = _swtCardNo.on;
  
  NSString* sEmail = _txtName.text;
  NSString* sPswd = _txtPswd.text;
  NSString *sSex = [NSString stringWithFormat:@"%i", (int)_scSex.selectedSegmentIndex];
  
  NSString* sTagId = _lblCardNo.text;
  if(bUpdCardNo) {
    NSString* sUrl = @"Host/-4";
    
    NSDictionary *measInfo = @{
                               @"BodyId" : [NSString stringWithFormat:@"%ld", (long)_nUserId],
                               @"BodyTagId" : sTagId,
                               @"Gender" : sSex
                               };
    
    
    NSMutableURLRequest *request = [pApp requestWebApiRouter:@"PUT" url:sUrl data:measInfo];
    
    // 6.同步发送请求
    //[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    NSData *data= [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(data != nil) {
      NSString* sRecv = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
      sRecv = [sRecv substringWithRange: NSMakeRange(1, sRecv.length-2)];
      if([sRecv hasPrefix:@"Failed"] || [sRecv rangeOfString:@"error"].location != NSNotFound) {
        [self _showAlert:@"Error Happened" msg: sRecv];
        [m_pViewCtrl runstopIndicator:NO];
        return;
      }
      [pApp updateMembBodyInfo:_nUserId tagId:sTagId email:nil rmv:NO];
    }
    //upd tagid end
  }
  else {
    NSString* sRmv = (_scRemoveFrGrp.selectedSegmentIndex == 1)? @"1": @"0";
    NSString* sUrl = @"Host/-3";
    NSDictionary *measInfo = @{
                               @"BodyId" : [NSString stringWithFormat:@"%ld", (long)_nUserId],
                               @"Email" : sEmail,
                               @"Password": sPswd,
                               @"Gender" : sSex,
                               @"_nRmvFrGrp" : sRmv
                               };
                              
    
    NSMutableURLRequest *request = [pApp requestWebApiRouter:@"PUT" url:sUrl data:measInfo];
    
    // 6.同步发送请求
    //[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
    NSData *data= [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    if(data != nil) {
      NSString* sRecv = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
      sRecv = [sRecv substringWithRange: NSMakeRange(1, sRecv.length-2)];
      if([sRecv hasPrefix:@"Failed"] || [sRecv rangeOfString:@"error"].location != NSNotFound) {
        [self _showAlert:@"Error Happened" msg: sRecv];
        return;
      }
      if([pApp updateMembBodyInfo:_nUserId tagId:nil email:sEmail rmv:[sRmv isEqualToString:@"1"]]) {
        UIAlertView* alert=[[UIAlertView alloc]initWithTitle:@"Active Acct Tip" message:@"The User need to receive email and active the acccount by click a hyperlink"
                                                    delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"OK", nil),nil];
        [alert show];
      }
    }
    //upt acct end
  }
  [self viewDisappear];
  [self hideUser];
  [m_pViewCtrl refreshMembData];
}

- (IBAction)doSaveAction:(id)sender {
  //if(_bNeedClrTagId)
    //[self sendDeviceRandTagIds:_ScanRQCode clear:YES];
  if(sender == _btnDisable) {
    _bComfirmEnd = NO;
    UIAlertView* alert=[[UIAlertView alloc]initWithTitle:NSLocalizedString(@"DisIDComfimTit", nil) message:NSLocalizedString(@"DisIDComfimMsg", nil) delegate:self cancelButtonTitle:@"YES"otherButtonTitles:@"NO",nil];
    [alert show];
  }
  else if(sender == _btnSave) {
    [m_pViewCtrl runstopIndicator:YES];
      
    NSString* sName = _txtName.text;
    if(!_swtCardNo.on && sName.length == 0) {
      [m_pViewCtrl runstopIndicator:NO];
      UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Name or Email" message:
                                @"The Name or Email is not empty!\n Please check it."
                                delegate:self cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil];
      [alertView show];
      [m_pViewCtrl runstopIndicator:NO];
      return;
    }
    //int nSex = (int)_scSex.selectedSegmentIndex;
    if((!_txtPswd.hidden && !_lblCardNo.hidden) || _swtCardNo.on) {   //upgrade to create acct or update tagid
      NSString* sPswd = _txtPswd.text;
      NSString* sCardNo = _lblCardNo.text;
      NSString* sScaleNo = _lblScaleNo.text;
        
      if(_swtCardNo.on) { //replacr Tag Id only
        if([sCardNo hasPrefix:@"..."]) {
          [m_pViewCtrl runstopIndicator:NO];
          [self _showAlert: @"Tag ID Is Needed" msg:@"Please scan Tag ID on scale"];
          [m_pViewCtrl runstopIndicator:NO];
          return;
        }
        sName = @"**";
        sPswd = @"**";
      }
      else {
        NSRange rng = [sName rangeOfString:@"@"];
        if(rng.location == NSNotFound) {
          [self _showAlert:@"Email without '@'!" msg: @"Check your enter."];
          [m_pViewCtrl runstopIndicator:NO];
          return;
        }
        rng = [sName rangeOfString:@"."];
        if(rng.location == NSNotFound) {
          [self _showAlert:@"Email without '.'!" msg: @"Check your enter."];
          [m_pViewCtrl runstopIndicator:NO];
          return;
        }
      }
        
      if([sCardNo hasPrefix:@"..."])
        sCardNo = @"00";
      if([sScaleNo hasPrefix:@"..."])
        sScaleNo = @"00";
            
      if(!_swtCardNo.on) {
        if(![self passCheckFields:sName pswd:sPswd]) {
          [m_pViewCtrl runstopIndicator:NO];
          return;
        }
      }
      [self ugdMemberBodyInfo];
      return;
    }
        
    NSString* sWgt = _txtBodyWgt.text;
    if(sWgt.length == 0) {
      [m_pViewCtrl runstopIndicator:NO];
      [self onTapGetBodyWgt:nil];
      UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Body WGT" message:
                                @"The WGT is not empty! after scan QR code on WiFi scale. \n Please Step on WiFi scale to get it."
                                delegate:self cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil];
      [alertView show];
      return;
    }
    //int nWun = (int)_scWgtUnit.selectedSegmentIndex +1;
    NSString* sHgt = _txtBodyHgt.text;
    //int sHun = (int)_txtHgtInch.hidden? 1:2;
    if(sWgt.length == 0)
      sWgt = @"0";
    if(sHgt.length == 0)
      sHgt = @"0";
        
    //check hgt
    double dHgt = [sHgt floatValue];
    //float fHgt = dHgt;
    float fHgtIn = 0;
    if(!_txtHgtInch.hidden) {
      fHgtIn = _txtHgtInch.text.floatValue / 12;
      dHgt += fHgtIn;
      //fHgt = dHgt;
      sHgt = [NSString stringWithFormat:@"%.3f", dHgt];
      dHgt *= _FtToMeter;
    }
    if(dHgt < 0.5 || dHgt > 2.27) {
      [m_pViewCtrl runstopIndicator:NO];
      UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Body Height?" message:
                                @"The height is out of range!\n Please check it."
                                delegate:self cancelButtonTitle:NSLocalizedString(@"OK", nil) otherButtonTitles:nil];
      [alertView show];
      return;
    }
    
    AppDelegate* pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [self saveBodyPrfData: pApp.m_bodyInfo.m_nBodyId card:@"00000000"];
    //[pApp insertMembGroupInfo:sBodyId, (long)_nUserId, sName, sWgt, nWun, sHgt, sHun, sBorn, nSex, nExeLvl];
    /*NSArray* listItems = [sName componentsSeparatedByString:@" "];
    NSUInteger n = listItems.count;
    if( n > 1) {
      sName = [sName stringByReplacingOccurrencesOfString:@" " withString:@"&"];
    }*/
        
    /*if(_socketSvr) {
      short nExeLvl = 0;
      NSString* sMsg = [NSString stringWithFormat:@"1234 %s: %@ %li %@ %@ %i %@ %i %@ %i %i \r\n", _szUpdUser,
                        pApp.sBodyId, (long)_nUserId, sName, sWgt, nWun, sHgt, sHun, sBorn, nSex, nExeLvl];
      [_socketSvr userSignin:(char *)[sMsg UTF8String] Alert:YES];
            
    }*/
    [self viewDisappear];
    [self hideUser];
  }
  else {
    [self viewDisappear];
    [self hideUser];
  }
  //[hourFormat release];
}


#pragma mark - BLE init
- (void) initBLEScale
{
    BOOL bConnWiFi = _bNcitDevice;//[self isNcitDevice];
    //BLE ini
    _bRcvBLeData = NO;
    _autoConnect = YES;//NO;
    
    AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    _ncitBleDev = pApp.m_ncitBleDev;
    _ncitBleDev.bleDelegate = self;
    [_ncitBleDev startMeas:@"FFF0"];
    
    //[self SetToolBarWiFiBLe:bConnWiFi];
    _bFirstConnBLe = !bConnWiFi;
    
    //_lblConn.text = sConnUuid;
}

- (double) getVdrBleLbWgtVal
{
    int nWgtLb = (int)((_nLastWgtVal * 10 * 0x2B0F / 0xC350 + 1) / 2) * 2;
    double dWgtLb = nWgtLb / 10.0;
    return dWgtLb;
}

//- (void) updateBleWgtata:(NSData *)data
- (void) updateBLeWgtData:(double)dWgt fat:(float)fFat wat:(float)fWat mus:(float)fMus bone:(float)fBone wUnit:(short)nUn hgt:(float)fHgt
{
    //AppDelegate *pApp = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    /*const uint8_t *reportData = [data bytes];
    uint8_t bWgth, bWgtl;
    uint8_t bStart = reportData[0];*/
    
    /*BOOL bFatWat = NO;
    float dFatVal = 0.0f, dWatVal = 0.0f;
    if(bStart == 0xCf) {
        bFatWat = YES;
        bWgth = reportData[4];
        bWgtl = reportData[5];
        
        uint8_t bFath = reportData[6];
        uint8_t bFatl = reportData[7];
        dFatVal = ((bFath << 8) + bFatl) / 10.0;
        
        uint8_t bWath = reportData[12];
        uint8_t bWatl = reportData[13];
        dWatVal = ((bWath << 8) + bWatl) / 10.0;
        
        //if(dFatVal > 0 && dWatVal > 0) {
            //NSString* sInfo = [NSString stringWithFormat:@"FAT: %.1f %%,  TBW: %.1f %%", dFatVal, dWatVal];
            //_lblOthMeas.text = sInfo;
        //}
    }
    else {
        bWgth = reportData[2];
        bWgtl = reportData[3];
        //glass ble scale
        if(bWgtl == 0 && bWgth == 0) {
            bWgth = reportData[4];
            bWgtl = reportData[5];
        }
    }
    
    _nLastWgtVal = ((bWgth << 8) + bWgtl);
    double dWgtVal = _nLastWgtVal / 10.0;
    _dLastWgt = dWgtVal;*/
    //_txtBodyWgt.text = [NSString stringWithFormat:@"%.1f", dWgtVal];
    //_scWgtUnit.selectedSegmentIndex = 0;
    
    _dLastWgt = dWgt;
    _scWgtUnit.selectedSegmentIndex = 0;
    [self wgtUnitChged: _scWgtUnit];

    _bContBleScale = NO;
}

#pragma mark - BLE center delegate methods

- (void) sendDataToBleDev:(CBCharacteristic*)aChar
{
    if(_ncitBleDev.m_pBleDevPer != nil) {
        uint8_t val[8] = {0xFE, 0x03, 0x01, 0x00, 0xAA, 0x19, 0x01, 0xB0};
        NSData* valData = [NSData dataWithBytes:(void*)&val length:sizeof(val)];
        [_ncitBleDev.m_pBleDevPer writeValue:valData forCharacteristic:aChar type:CBCharacteristicWriteWithResponse];
    }
}

//- (void) recvedBleWgtData: (NSData *)data
- (void) recvedBleWgtData:(double)dWgt fat:(float)fFat wat:(float)fWat mus:(float)fMus bone:(float)fBone wUnit:(short)nUn fatwatInc:(BOOL)bFatWat hgt:(float)fHgt
{
    [_ncitBleDev stopMeas];
    if(_isPopup) {
        if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7)
            AudioServicesPlaySystemSound(1115);
        else
            AudioServicesPlaySystemSound(1315);
        
        //[self updateBleWgtata:data];
        [self updateBLeWgtData:dWgt fat:fFat wat:fWat mus:fMus bone:fBone wUnit:nUn hgt:fHgt];
    }
    _bRcvBLeData =YES;
}

//bluetooth start
/*- (void) startScan
{
    if(!_bIsSuptBLe)
        return;
    _bContBleScale = YES;
    [manager scanForPeripheralsWithServices:[NSArray arrayWithObject:[CBUUID UUIDWithString:@"FFF0"]] options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @NO }];
    //[manager scanForPeripheralsWithServices:[NSArray arrayWithObject:[CBUUID UUIDWithString:@"FFF0"]] options:nil];
}

- (void) stopScan
{
    if(!_bIsSuptBLe)
        return;
    [manager stopScan];
    //[self _stopProgressView];
}

- (void) centralManagerDidUpdateState:(CBCentralManager *)central
{
    _bIsSuptBLe = [self isLECapableHardware];
    if(_bIsSuptBLe) {
        //[self loadSavedDevices];
        //[manager retrieveConnected
        if (_bFirstConnBLe) {
            [self startScan];
        }
        //if([_lblInfo.text hasPrefix:@"At"])
            //_lblState.text = @"With Accuro BLE scale, step on it";
    }
}

- (void) centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)aPeripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    if(aPeripheral == nil)
        return;
    
    //NSMutableArray *peripherals = [self mutableArrayValueForKey:@"hrConntMonitors"];
    BOOL bExists = [hrConntMonitors containsObject:aPeripheral];
    if(!bExists) {
        [hrConntMonitors addObject:aPeripheral];
        
        if(_autoConnect) {
            _peripheral = aPeripheral;
            [manager connectPeripheral:_peripheral options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:CBConnectPeripheralOptionNotifyOnDisconnectionKey]];
            ////[manager connectPeripheral:aPeripheral options:nil];
            [self stopScan];
            if(!_txtBodyWgt.hidden)
                _lblConnTip.text = @"Ready";//@"BLE Scale Ready";
        }
    }
}

- (void) centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)aPeripheral
{
    [aPeripheral setDelegate:self];
    [aPeripheral discoverServices:nil];
    
    if (![hrConntMonitors containsObject:aPeripheral])
		[hrConntMonitors addObject:aPeripheral];
    
    //_peripheral = aPeripheral;
    _bRcvBLeData = NO;
}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)aPeripheral error:(NSError *)error
{
    CBPeripheral* service = nil;
    for (service in hrConntMonitors) {
        if (service == aPeripheral) {
            [hrConntMonitors removeObject:service];
            //[peripheralDelegate alarmServiceDidChangeStatus:service];
            break;
        }
    }
    
    //if(_bContBleScale) {
        //_lblState.text = @"Scale BLE Power off, Step...";
        if(_peripheral != nil) {
            [manager cancelPeripheralConnection:_peripheral];
            _peripheral = nil;
        }
        [self startScan];
    //if(_isPopup && !_txtBodyWgt.hidden)
        //AudioServicesPlaySystemSound(1112);
    _lblConnTip.text = @"BLE...";//@"BLE Scale Hibernate";
}

- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)aPeripheral error:(NSError *)error
{
    NSLog(@"Fail to connect to peripheral: %@ with error = %@", aPeripheral, [error localizedDescription]);
    //[connectButton setTitle:@"Connect"];
    if( _peripheral != nil && _peripheral == aPeripheral)
    {
        [_peripheral setDelegate:nil];
        //[_peripheral release];
        _peripheral = nil;
    }
    //_lblState.text = [NSString stringWithFormat: @"%@ %s", [aPeripheral name], "Fail to connect"];
}

- (void) centralManager:(CBCentralManager *)central didFailToRetrievePeripheralForUUID:(CFUUIDRef)UUID error:(NSError *)error
{
	//[self removeSavedDevice:UUID];
}

#pragma mark - CBPeripheral delegate methods
- (void) peripheral:(CBPeripheral *)aPeripheral didDiscoverServices:(NSError *)error
{
    for (CBService *aService in aPeripheral.services)
    {
        NSLog(@"Service found with UUID: %@", aService.UUID);
        
        // Heart Rate Service
        //if ([aService.UUID isEqual:[CBUUID UUIDWithString:@"180D"]])
        NSString* sBLeName = aService.peripheral.name;
        //NSString* sIdentifier = aService.peripheral.identifier.UUIDString;
        if ([aService.UUID isEqual:[CBUUID UUIDWithString:@"FFF0"]] || [sBLeName isEqualToString:@"Electronic Scale"]) {
            [aPeripheral discoverCharacteristics:nil forService:aService];
            //txtData.text = [NSString stringWithFormat: @"%@ %s", [[aService peripheral] name], "found"];//@"Heart Rate Service found";
        }
        
    }
}

- (void) peripheral:(CBPeripheral *)aPeripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    if ([service.UUID isEqual:[CBUUID UUIDWithString:@"FFF0"]]) {
        for (CBCharacteristic *aChar in service.characteristics) {
            // Set notification on heart rate measurement
            if ([aChar.UUID isEqual:[CBUUID UUIDWithString:@"FFF4"]])
            {
                [_peripheral setNotifyValue:YES forCharacteristic:aChar];
                NSLog(@"Found a BLE Electronic Scale Measurement Characteristic");
            }
        }
    }
    
    //write to peripheral
    if ([service.UUID isEqual:[CBUUID UUIDWithString:@"FFF0"]]) {
        for (CBCharacteristic *aChar in service.characteristics) {
            
            // Set notification on heart rate measurement
            //if ([aChar.UUID isEqual:[CBUUID UUIDWithString:@"2A37"]])
        
            
            // Write heart rate control point
            //if ([aChar.UUID isEqual:[CBUUID UUIDWithString:@"2A39"]]) {
            if ([aChar.UUID isEqual:[CBUUID UUIDWithString:@"FFF1"]]) {
                uint8_t val[8] = {0xFE, 0x03, 0x01, 0x00, 0xAA, 0x19, 0x01, 0xB0};
                NSData* valData = [NSData dataWithBytes:(void*)&val length:sizeof(val)];
                [aPeripheral writeValue:valData forCharacteristic:aChar type:CBCharacteristicWriteWithResponse];
                //[aPeripheral writeValue:valData forCharacteristic:aChar type:CBCharacteristicWriteWithResponse];
            }
        }
    }
    
}

- (void) peripheral:(CBPeripheral *)aPeripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error
{
    //if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"2A24"]]) {
    if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"FFF4"]]) {
        if( (characteristic.value)  || !error ) {
            // Update UI with heart rate data
            if(_bRcvBLeData)
                return;
            if(_isPopup && !_txtBodyWgt.hidden) {
                if([[[UIDevice currentDevice] systemVersion] floatValue] >= 7)
                    AudioServicesPlaySystemSound(1115);
                else
                    AudioServicesPlaySystemSound(1315);
            
                [self updateBleWgtata:characteristic.value];
            }
            _bRcvBLeData =YES;
            //[self SetBleNotAvaiable];
            
            //[self updateBleWgtata:characteristic.value];
            return;
        }
    }
    // Value for body sensor location received
    else if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"2A38"]])
    {
        NSData * updatedValue = characteristic.value;
        uint8_t* dataPointer = (uint8_t*)[updatedValue bytes];
        if(dataPointer)
        {
            uint8_t location = dataPointer[0];
            NSString*  locationString;
            switch (location)
            {
                case 0:
                    locationString = @"Other";
                    break;
                case 1:
                    locationString = @"Chest";
                    break;
                case 2:
                    locationString = @"Wrist";
                    break;
                case 3:
                    locationString = @"Finger";
                    break;
                case 4:
                    locationString = @"Hand";
                    break;
                case 5:
                    locationString = @"Ear Lobe";
                    break;
                case 6:
                    locationString = @"Foot";
                    break;
                default:
                    locationString = @"Reserved";
                    break;
            }
            NSLog(@"Body Sensor Location = %@ (%d)", locationString, location);
        }
    }
}*/

#pragma mark -QR code scan
/*- (BOOL)startQRReading {
    NSError *error;
    
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (!input) {
        NSLog(@"%@", [error localizedDescription]);
        return NO;
    }
    
    _cptQRSession = [[AVCaptureSession alloc] init];
    [_cptQRSession addInput:input];
    
    AVCaptureMetadataOutput *captureMetadataOutput = [[AVCaptureMetadataOutput alloc] init];
    [_cptQRSession addOutput:captureMetadataOutput];
    
    dispatch_queue_t dispatchQueue;
    dispatchQueue = dispatch_queue_create("myQueue", NULL);
    [captureMetadataOutput setMetadataObjectsDelegate:self queue:dispatchQueue];
    [captureMetadataOutput setMetadataObjectTypes:[NSArray arrayWithObject:AVMetadataObjectTypeQRCode]];
    
    _cvpQRLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:_cptQRSession];
    [_cvpQRLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
    [_cvpQRLayer setFrame:_viewQRcode.layer.bounds];
    [_viewQRcode.layer addSublayer:_cvpQRLayer];
    
    [_cptQRSession startRunning];
    
    return YES;
}

-(void)stopQRReading{
    [_cptQRSession stopRunning];
    _cptQRSession = nil;
    
    [_cvpQRLayer removeFromSuperlayer];
    
    _viewQRcode.hidden = YES;
   //_lblScanTips.hidden = YES;
}

- (void)startStopReading {
    if(_viewQRcode == nil) {
        CGFloat xPos = (self.frame.size.width - 160) / 2;
        CGFloat yPos = 80;
        CGRect rt = CGRectMake(xPos, yPos, 160, 160);
        _viewQRcode = [[UIView alloc] initWithFrame:rt];
        _viewQRcode.layer.masksToBounds = YES;
        _viewQRcode.layer.cornerRadius = 4;
        [self addSubview:_viewQRcode];
    }
    _viewQRcode.hidden = NO;//bOpen;
    if (!_bQrReading) {
        if ([self startQRReading]) {
            //_lblScanTips.hidden = NO;
            _lblScanTips.text =  [NSString stringWithFormat:@"%@, %@", NSLocalizedString(@"TitScanQr", nil),
                                  NSLocalizedString(@"ThenTagId", nil)];
            //_lblScanTips.textColor = [UIColor redColor];
            //_lblCardNo.text = @"Scan It...";
        }
        _bSendTagDevInfo = NO;
    }
    else{
        [self stopQRReading];
        _lblScanTips.text = @"";
        //_lblScanTips.hidden = YES;
        //[self sendRandTagId:YES];
    }
    
    _bQrReading = !_bQrReading;
}

-(void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{
    if (metadataObjects != nil && [metadataObjects count] > 0) {
        AVMetadataMachineReadableCodeObject *metadataObj = [metadataObjects objectAtIndex:0];
        if ([[metadataObj type] isEqualToString:AVMetadataObjectTypeQRCode]) {
            if(!_bQrReading)
                return;
            
            //m_bResolved = YES;
            _ScanRQCode = [metadataObj stringValue];
            [self performSelectorOnMainThread:@selector(stopQRReading) withObject:nil waitUntilDone:NO];
            //[self stopQRReading];
            [_lblScaleNo performSelectorOnMainThread:@selector(setText:) withObject:[metadataObj stringValue] waitUntilDone:NO];
            
            AudioServicesPlaySystemSound(1115);
            [self sendDeviceRandTagIds: _ScanRQCode clear:NO];
            _bQrReading = NO;
            
            _swtCardNo.on = YES;
            _btnSave.enabled = NO;
        }
    }
}*/

- (void) touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
  if(_wmtWgtType != nil && !_wmtWgtType.hidden) {
    _wmtWgtType.hidden = YES;
    _btnBodyWgt.hidden = NO;
  }
  [self endEditing:YES];
}
#pragma mark -QR code end

/*- (void) sendDeviceRandTagIds:(NSString*)sDevId clear:(BOOL)bClear
{
    char szTagIdNo[64] = "";
    //NSString* sTagId = @"Upd**123456";
     NSString* sTagId = _lblCardNo.text;
    if(sTagId.length > 16)
        sTagId = [sTagId substringToIndex:16];
    
    strcpy(szTagIdNo, "1234 ");
    if(bClear) {
        strcat(szTagIdNo, "TagIdClr=");
    }
    else {
        strcat(szTagIdNo, "TagId=");
        strcat(szTagIdNo, "Upd");
    }
    strcat(szTagIdNo, [sTagId UTF8String]);
    strcat(szTagIdNo, "DevId=");
    strcat(szTagIdNo, [sDevId UTF8String]);
    strcat(szTagIdNo, "\r\n");
    
    //if(_socketSvr)
      //[_socketSvr sendData:szTagIdNo Alert:NO];
    //if(bClear)
        //_lblScanTips.hidden = YES;
    _bNeedClrTagId = !bClear;
}*/

@end
